package com.zephyr.vchcenter.pbcFile.util;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.zephyr.vchcenter.pbcFile.configBean.Dict;
import com.zephyr.vchcenter.pbcFile.exception.MatchException;

public abstract class XMLParserUtil {
	

	private static Logger log = Logger.getLogger(XMLParserUtil.class);

	public Document getDocument(File file/* ,String str */) {

		SAXReader sr = new SAXReader();
		sr.setEncoding("utf-8");
		log.debug(sr.getEncoding());
		Document d = null;
		try {
			// d=DocumentHelper.parseText(str);
			d = sr.read(file);
		} catch (Exception e) {
			log.debug("match exception::getDocument failed", e);
			//log.error("CParser::getDocument Error", e);
			throw new MatchException("getDocument Error");
			
		}
		return d;
	}

	/**
	 * @author zhaoyunxiao 
	 */
	public Element getRoot(Document document) {

		return document.getRootElement();
	}

	/**
	 * @author zhaoyunxiao 
	 */
	public Iterator<Element> getIterator(Element e) {

		return e.elementIterator();
	}

	/**
	 * @author zhaoyunxiao 
	 */
	public Element getElement(File file, String str) {
		Document doc = getDocument(file);

		Element element = null;

		Element root = getRoot(doc);
		for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
			element = it.next();
			if (element.getName().equals(str)) {
				break;
			}
		}
		return element;
	}

	public String getItem(Element e) {
		StringBuffer sbf = new StringBuffer();
		for (Iterator<Element> it = e.elementIterator(); it.hasNext();) {
			Element element = it.next();
			if (element.getTextTrim().length() > 0) {
				sbf.append(element.getTextTrim() + ":");
			} else if (element.getText().length() == 0) {
				sbf.append("    :"); 
			} else {
				sbf.append(getItem(element));
			}
		}

		return sbf.deleteCharAt(sbf.length() - 1).toString();
	}

	public List<String> getAnyElements(Element root, String elementName) {
		Iterator<Element> it = getIterator(root);
		List<String> list = new ArrayList<String>();
		while (it.hasNext()) {
			Element e = it.next();
			if (e.getName().equals(elementName)) {
				list.add(getItem(e));
			} else {
				list.addAll(getAnyElements(e, elementName));
			}
		}
		return list;
	}
}
